using Digitalmes.Application.Scada.Commands;
using ThingsEdge.Exchange.Contracts;
using ThingsEdge.Exchange.Forwarders;

namespace Digitalmes.Infrastructure.Scada.Handlers;

/// <summary>
/// 设备警报处理。
/// </summary>
internal sealed class EquipmentAlarmHandler(ISender sender) : IScadaTellHandler
{
    private static readonly Holder<bool[]> _alarmHolder = new(); // 存储上一次的警报记录

    public async Task HandleAsync(NoticeContext context, CancellationToken cancellationToken = default)
    {
        var message = context.Message;
        var alarmData = message.Self().GetBitArray();

        EquipmentAlarmCommand command = new()
        {
            LineCode = message.Schema.ChannelName,
            DeviceName = message.Schema.DeviceName,
            WsCode = message.Schema.TagGroupName,
            AlarmData = alarmData,
            LastAlarmData = _alarmHolder.Data ?? [],
        };

        await sender.Send(command, cancellationToken);

        _alarmHolder.Data = alarmData;
    }

    private sealed class Holder<T>
    {
        public T? Data { get; set; }
    }
}
